package com.mall.order.mq;

import com.alibaba.fastjson.JSON;
import com.mall.order.OrderCoreService;
import com.mall.order.OrderPromoService;
import com.mall.order.constant.OrderRetCode;
import com.mall.order.dal.entitys.OrderItem;
import com.mall.order.dal.persistence.OrderItemMapper;
import com.mall.order.dto.CartProductDto;
import com.mall.order.dto.CreateOrderRequest;
import com.mall.order.dto.CreateOrderResponse;
import com.mall.order.dto.CreateSeckillOrderRequest;
import com.mall.shopping.IProductService;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.math.BigDecimal;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;


/**
 * 消费者
 */
@Component
public class CreatePromoOrderConsumer {

    private DefaultMQPushConsumer consumer;

    @Autowired
    OrderPromoService orderPromoService;

    @Autowired
    OrderCoreService orderCoreService;

    @Autowired
    OrderItemMapper orderItemMapper;

    @Reference(check = false)
    IProductService service;



    @PostConstruct
    public void init() {
        consumer = new DefaultMQPushConsumer("create_promo_order_consumer");
        consumer.setNamesrvAddr("127.0.0.1:9876");
        try {
            consumer.subscribe("mqtop", "*");
        } catch (MQClientException e) {
            e.printStackTrace();
        }
        consumer.setMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
                MessageExt message = msgs.get(0);
                    byte[] body = message.getBody();
                String requestStr = new String(body, 0, body.length, Charset.forName("utf-8"));
                CreateSeckillOrderRequest request = JSON.parseObject(requestStr, CreateSeckillOrderRequest.class);

//                CreateSeckillOrderResponse promoOrder = orderPromoService.createPromoOrder(request);

                CreateOrderRequest createOrderRequest = new CreateOrderRequest();
                BigDecimal orderTotal = request.getPrice();
                //价格
                createOrderRequest.setOrderTotal(orderTotal);
                //userid
                Long userId = request.getUserId();
                createOrderRequest.setUserId(userId);
                //username
                String username = request.getUsername();
                createOrderRequest.setUserName(username);
                //uuid
                createOrderRequest.setUniqueKey(UUID.randomUUID().toString());


                createOrderRequest.setTel(request.getTel());
                createOrderRequest.setStreetName(request.getStreetName());
                createOrderRequest.setAddressId(request.getAddressId());

                CartProductDto cartProductDto = new CartProductDto();
                ArrayList<CartProductDto> list = new ArrayList<>();
                //price
                cartProductDto.setSalePrice(request.getPrice());
                //produc
                cartProductDto.setProductId(request.getProductId());
                //选中状态
                cartProductDto.setChecked("true");
                cartProductDto.setProductNum(1L);


//                Example example = new Example(OrderItem.class);
//                Example.Criteria criteria = example.createCriteria();
                OrderItem orderItem = new OrderItem();
//                criteria.andEqualTo("itemId",request.getProductId());
                    orderItem.setItemId(request.getProductId());


                Map map =    service.getItem(request.getProductId());


//                OrderItem item = orderItemMapper.selectByPrimaryKey(orderItem);


//                OrderItem item = orderItemMapper.selectByExample(orderItem,example);
                Object image = map.get("image");
                String image1 = (String) image;
                String[] split = image1.split(",");
                cartProductDto.setProductImg(split[0]);


                cartProductDto.setProductName((String)map.get("title"));

                list.add(cartProductDto);
                createOrderRequest.setCartProductDtoList(list);

                CreateOrderResponse promoOrder = orderCoreService.createOrder(createOrderRequest);


                // 根据调用结果决定，返回消费成功还是失败
                if (OrderRetCode.SUCCESS.getCode().equals(promoOrder.getCode())) {
                    //下单成功了
                    return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
                }
                //事务下部分失败,需要重试
                return ConsumeConcurrentlyStatus.RECONSUME_LATER;
            }
        });



        try {
            consumer.start();
        } catch (MQClientException e) {
            e.printStackTrace();
        }
    }

}
